package com.vincent.music.kkmusicapi.services;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vincent.music.kkmusicapi.config.OkHttpClientConfig;
import com.vincent.music.kkmusicapi.http.ApiCallback;
import com.vincent.music.kkmusicapi.http.ApiJsonCallback;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Base64;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class ApiService {

    //    private final OkHttpClient okHttpClient;
    @Autowired
    OkHttpClientConfig okHttpClientConfig;
//
//    public ApiService(@Autowired OkHttpClient okHttpClient) {
//        this.okHttpClient = okHttpClient;
//    }

    public <T> ApiCallback<T> sendRequest(String url) {
        Request request = new Request.Builder().url(url).build();
        Response response;
        try {
            response = okHttpClientConfig.okHttpClient().newCall(request).execute();
            if (!response.isSuccessful()) {
                return ApiCallback.failed("Response Failed");
            }
            Gson gson = new Gson();
            String result = Objects.requireNonNull(response.body()).string();
            ApiCallback apiCallback = gson.fromJson(result, ApiCallback.class);
            if (null != apiCallback) {
                System.err.println("返回结果：" + unicodeToString(URLDecoder.decode(gson.toJson(apiCallback), "UTF-8")));
            }
            return apiCallback;
        } catch (Exception e) {
            return ApiCallback.error(e.getMessage());
        }
    }

//    public static void main(String[] args) {
//        String url = "https://st.music.163.com/encrypt-pages?params\\u003d{\"sign\":\"6c592451f3f1eb02168d781b685472f6\",\"event_id\":\"00433901731967168544\"}\\u0026verifyType\\u003d40\\u0026verifyId\\u003d1007602\\u0026verifyToken\\u003d00.40.5b678ad754c152ad12e7ebf19dbcb3d4.767090559";
//        System.out.println(unicodeToString(url));
//    }

    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }
}
